package com.core.shared;

import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/8/2
 * Time: 16:42
 * To change this template use Editor | File and Code Templates.
 */
public class WebTimeUtil {

    private static final String WEB_TIME_NTSC = "http://www.ntsc.ac.cn";// 中国科学院国家授时中心
    private static final String WEB_TIME_BJ = "http://www.bjtime.cn";// bjTime
    private static final String WEB_TIME_BAIDU = "http://www.baidu.com";// 百度
    private static final String WEB_TIME_TAOBAO = "http://www.taobao.com";// 淘宝
    private static final String WEB_TIME_360 = "http://www.360.cn";// 360
    private static final String WEB_TIME_BEIJING = "http://www.beijing-time.org";// beijing-time
    private static final String WEB_TIME_JINGDONG = "http://www.jd.com/";// 京东
    private static String[] urlArrays = {WEB_TIME_NTSC, WEB_TIME_BJ, WEB_TIME_BAIDU, WEB_TIME_TAOBAO, WEB_TIME_360, WEB_TIME_BEIJING, WEB_TIME_JINGDONG};

    public static String getWebDatetime() {
        for (int i = 0; i < urlArrays.length; i++) {
            try {
                URL url = new URL(urlArrays[i]);
                URLConnection uc = url.openConnection();
                uc.connect();
                long ld = uc.getDate();
                Timestamp timestamp = new Timestamp(ld);
                return DateTimeUtils.DEFAULTFORMATTER.format(timestamp.toLocalDateTime());
            } catch (Exception e) {
                Log.getLogger(WebTimeUtil.class).error("getWebDateTime error,current use [{}]", urlArrays[i]);
            }
        }
        return DateTimeUtils.DEFAULTFORMATTER.format(LocalDateTime.now());
    }

    public static String getWebDatetime(String webuUrl) {
        try {
            if (!CommonUtils.isEmpty(webuUrl)) {
                URL url = new URL(webuUrl);
                URLConnection uc = url.openConnection();
                uc.connect();
                long ld = uc.getDate();
                Timestamp timestamp = new Timestamp(ld);
                return DateTimeUtils.DEFAULTFORMATTER.format(timestamp.toLocalDateTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
